package com.util;

import android.util.Base64;

import com.bean.LoginSuccessBean;
import com.google.gson.Gson;
import com.google.gson.JsonArray;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mars on 2017/9/28.
 */

public class JsonUtils {

    private static Gson jsonUtils;

    private static Gson getInstance() {
        if (jsonUtils == null) {
            jsonUtils = new Gson();
        }
        return jsonUtils;
    }

    public static <T> T getResult(String jsonStr, Class<T> t) {
        return getInstance().fromJson(jsonStr, t);
    }

    public static <T> List<T> getResultList(JsonArray array, Class c) {
        List<T> list = new ArrayList<>();
        if (array != null) {
            int size = array.size();
            Gson gson = new Gson();
            for (int i = 0; i < size; i++) {
                list.add((T) gson.fromJson(array.get(i), c));
            }
        }

        return list;
    }

    /**
     * 解析未Base64解码的数组
     *
     * @param body
     * @param t
     */
    public static <T> T getByteJsonResult(byte[] body, Class<T> t) {
        byte[] decode = Base64.decode(body, Base64.DEFAULT);
        String s = new String(decode);
        return getInstance().fromJson(s, t);
    }
}
